package com.cuke.entityhelper.utils;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class PsiElementUtils {

    /**
     * 获取光标处的元素
     *
     * @param editor
     * @param file
     * @return
     */
    @Nullable
    public static PsiElement getElement(@NotNull Editor editor, @NotNull PsiFile file) {
        CaretModel caretModel = editor.getCaretModel();
        int position = caretModel.getOffset();
        return file.findElementAt(position);
    }

    /**
     * 获取光标所在的类 PsiClass对象,而不是当前文件对应的类, 考虑到内部类的场景
     *
     * @param e
     * @return
     */
    public static PsiClass getPsiClassFromCursor(AnActionEvent e) {
        Project project = e.getProject();

        //应该获取光标所在的类,而不是当前文件对应的类, 考虑到内部类的场景
        //PsiClass psiClass = PsiClassUtils.getPsiClassFromContext(e);

        Editor editor = e.getData(PlatformDataKeys.EDITOR);
        PsiFile file = e.getData(PlatformDataKeys.PSI_FILE);
        if (project == null || editor == null || file == null) {
            return null;
        }
        //获取光标所在元素
        PsiElement element = PsiElementUtils.getElement(editor, file);

        PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
        if (psiClass == null) {
            return null;
        }
        //当前光标所在地方是一个 class 里面 (如果光标在内部类里面,则返回内部类对象)
        //System.out.println("psiClass.getText():" + psiClass.getText());
        return psiClass;
    }
}
